<template>
	<template v-if="is_avatar">
		<button class="avatar-upload p-0 m-0 rounded" hover-class="none" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
			<view :style="{ width: size + 'rpx', height: size + 'rpx', backgroundColor: bgColor, borderRadius: rounded }" @click="getIMG">
				<image :style="{ width: size + 'rpx', height: size + 'rpx', borderRadius: rounded }" :src="modelValue" v-if="modelValue != '' && modelValue != null" />
				<view v-else :style="{ width: size + 'rpx', height: size + 'rpx', fontSize: size / 7 + 'rpx' }" class="flex_center">
					<u-icon name="camera-fill" :size="size / 6" />
					{{ text_mag }}
				</view>
			</view>
		</button>
	</template>

	<view v-else :style="{ width: size + 'rpx', height: size + 'rpx', backgroundColor: bgColor, borderRadius: rounded }" @click="getIMG">
		<image :style="{ width: size + 'rpx', height: size + 'rpx', borderRadius: rounded }" :src="modelValue" v-if="modelValue != '' && modelValue != null" />
		<view v-else :style="{ width: size + 'rpx', height: size + 'rpx', fontSize: size / 6 + 'rpx' }" class="flex_center">
			<u-icon name="camera-fill" :size="size / 6" />
			{{ text_mag }}
		</view>
	</view>
</template>

<script lang="ts" setup>
import { CSSProperties, onUnmounted } from 'vue';
import { uploadImage } from '@/api/app';
const props = defineProps({
	modelValue: {
		type: String
	},
	token: {
		type: String,
		default: ''
	},
	size: {
		type: [String, Number],
		default: 150
	},
	bgColor: {
		type: String,
		default: '#f7f7f7'
	},
	rounded: {
		type: String,
		default: '12rpx'
	},
	text_mag: {
		type: String,
		default: '上传图片'
	},

	is_avatar: {
		type: Boolean,
		default: false
	}
});
const emit = defineEmits<{ (event: 'update:modelValue', value: string): void }>();
const getIMG = () => {
	console.log(111);
	uni.chooseMedia({
		count: 1,
		mediaType: ['image'],
		sourceType: ['album', 'camera'],
		camera: 'back',
		success: async (res: any) => {
			const tempFilePaths = res.tempFiles[0].tempFilePath;
			console.log(res.tempFiles[0]);
			// emit('update:modelValue', tempFilePaths);
			await uploadImage(tempFilePaths, 'MASTER',props.token).then((res: any) => {
				emit('update:modelValue', res?.data);
			});
		},
		fail(err) {
			console.log(err);
		}
	});
};
const chooseAvatar = async (e: any) => {
	const path = e.detail?.avatarUrl;
	console.log(e);
	if (path) {
		await uploadImage(path, 'MASTER',props.token).then((res: any) => {
			emit('update:modelValue', res?.data);
		});
	}
};
</script>

<style lang="scss" scoped>
.boxImg {
	border-radius: 12rpx;
}
.flex_center {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column; 
}
.avatar-upload {
	background: rgba(0, 0, 0, 0); 
	overflow: hidden;
	&::after { 
		border: none;
	}
}
</style>
